<template>
  <el-card class="build-analytics">
    <template #header>
      <div class="ba-header">
        <span>编译分析</span>
      </div>
    </template>

    <!-- 搜索区域 -->
    <div class="ba-search">
      <el-form :inline="true" :model="query" class="ba-form" @submit.prevent>
        <el-form-item label="时间">
          <el-date-picker
            v-model="query.timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            :editable="false"
            :clearable="true"
          />
        </el-form-item>
        <el-form-item label="用户">
          <el-input
            v-model="query.user"
            placeholder="输入用户名"
            clearable
            class="ba-user-input"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 指标展示区域 -->
    <div class="ba-metrics">
      <el-row :gutter="16">
        <el-col :xs="24" :sm="12" :md="8" :lg="6">
          <el-card shadow="hover" class="metric-card">
            <div class="metric-title">时间范围</div>
            <div class="metric-value">{{ displayTimeRange }}</div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6">
          <el-card shadow="hover" class="metric-card">
            <div class="metric-title">用户</div>
            <div class="metric-value">{{ query.user || '全部' }}</div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6">
          <el-card shadow="hover" class="metric-card">
            <div class="metric-title">全量成功平均编译时间</div>
            <div class="metric-value">{{ formatMsToMinSec(metrics.fullSuccessAvg) }}</div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6">
          <el-card shadow="hover" class="metric-card">
            <div class="metric-title">全量失败平均编译时间</div>
            <div class="metric-value">{{ formatMsToMinSec(metrics.fullFailureAvg) }}</div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6">
          <el-card shadow="hover" class="metric-card">
            <div class="metric-title">增量成功平均编译时间</div>
            <div class="metric-value">{{ formatMsToMinSec(metrics.incrementalSuccessAvg) }}</div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6">
          <el-card shadow="hover" class="metric-card">
            <div class="metric-title">增量失败平均编译时间</div>
            <div class="metric-value">{{ formatMsToMinSec(metrics.incrementalFailureAvg) }}</div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6">
          <el-card shadow="hover" class="metric-card">
            <div class="metric-title">编译成功平均时间</div>
            <div class="metric-value">{{ formatMsToMinSec(overallSuccessAvg) }}</div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6">
          <el-card shadow="hover" class="metric-card">
            <div class="metric-title">编译失败平均时间</div>
            <div class="metric-value">{{ formatMsToMinSec(overallFailureAvg) }}</div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </el-card>
</template>

<script setup lang="ts">
import { reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'

defineOptions({ name: 'BuildAnalytics' })

type TimeRange = [string, string] | null

const query = reactive<{ timeRange: TimeRange; user: string }>(
  {
    timeRange: null,
    user: '',
  },
)

const metrics = reactive({
  fullSuccessAvg: 0,
  fullFailureAvg: 0,
  incrementalSuccessAvg: 0,
  incrementalFailureAvg: 0,
})

// 暂存接口原始结果，后续再处理
const rawResponse = reactive<{ datalist: any[] }>({ datalist: [] })

const displayTimeRange = computed(() => {
  if (!query.timeRange) return '全部'
  const [start, end] = query.timeRange
  return `${start} ~ ${end}`
})

// 总体平均：基于原始数据按条目加权计算
const overallSuccessAvg = computed(() => {
  const list = rawResponse.datalist || []
  let sum = 0
  let count = 0
  list.forEach((row: any) => {
    const result = String(row?.build_result || '').toUpperCase()
    const dur = Number(row?.total_duration_ms)
    if (result === 'SUCCESS' && Number.isFinite(dur)) {
      sum += dur
      count += 1
    }
  })
  return count > 0 ? Math.round(sum / count) : 0
})

const overallFailureAvg = computed(() => {
  const list = rawResponse.datalist || []
  let sum = 0
  let count = 0
  list.forEach((row: any) => {
    const result = String(row?.build_result || '').toUpperCase()
    const isFail = result === 'FAILED' || result === 'FAILURE'
    const dur = Number(row?.total_duration_ms)
    if (isFail && Number.isFinite(dur)) {
      sum += dur
      count += 1
    }
  })
  return count > 0 ? Math.round(sum / count) : 0
})

async function handleSearch() {
  try {
    const params: Record<string, string> = {}
    if (query.timeRange && query.timeRange.length === 2) {
      const [start, end] = query.timeRange
      const toISOish = (s: string) => s.replace(' ', 'T')
      params.time_range = `${toISOish(start)},${toISOish(end)}`
    }
    if (query.user) {
      params.user = query.user
    }

    const resp = await request.get('/performance/compile_analysis/query', {
      params,
    })

    // 只缓存原始数据，后续再做统计处理
    const payload = (resp?.data ?? resp) as any
    const list = Array.isArray(payload?.data?.datalist)
      ? payload.data.datalist
      : Array.isArray(payload?.datalist)
      ? payload.datalist
      : []
    rawResponse.datalist = list

    computeCompileAverages()
  } catch (e) {
    ElMessage.error('查询失败')
  }
}

function handleReset() {
  query.timeRange = null
  query.user = ''
  Object.assign(metrics, {
    fullSuccessAvg: 0,
    fullFailureAvg: 0,
    incrementalSuccessAvg: 0,
    incrementalFailureAvg: 0,
  })
  rawResponse.datalist = []
}

function computeCompileAverages() {
  const list = rawResponse.datalist || []
  const acc = {
    FULL_SUCCESS: { sum: 0, count: 0 },
    FULL_FAILED: { sum: 0, count: 0 },
    INCREMENTAL_SUCCESS: { sum: 0, count: 0 },
    INCREMENTAL_FAILED: { sum: 0, count: 0 },
  }

  list.forEach((row: any) => {
    const mode = String(row?.compilation_mode || '').toUpperCase()
    const result = String(row?.build_result || '').toUpperCase()
    const isFail = result === 'FAILED' || result === 'FAILURE'
    const isSuccess = result === 'SUCCESS'
    const dur = Number(row?.total_duration_ms)
    if (!Number.isFinite(dur)) return

    if (mode === 'FULL' && isSuccess) {
      acc.FULL_SUCCESS.sum += dur
      acc.FULL_SUCCESS.count += 1
    } else if (mode === 'FULL' && isFail) {
      acc.FULL_FAILED.sum += dur
      acc.FULL_FAILED.count += 1
    } else if (mode === 'INCREMENTAL' && isSuccess) {
      acc.INCREMENTAL_SUCCESS.sum += dur
      acc.INCREMENTAL_SUCCESS.count += 1
    } else if (mode === 'INCREMENTAL' && isFail) {
      acc.INCREMENTAL_FAILED.sum += dur
      acc.INCREMENTAL_FAILED.count += 1
    }
  })

  metrics.fullSuccessAvg = acc.FULL_SUCCESS.count
    ? Math.round(acc.FULL_SUCCESS.sum / acc.FULL_SUCCESS.count)
    : 0
  metrics.fullFailureAvg = acc.FULL_FAILED.count
    ? Math.round(acc.FULL_FAILED.sum / acc.FULL_FAILED.count)
    : 0
  metrics.incrementalSuccessAvg = acc.INCREMENTAL_SUCCESS.count
    ? Math.round(acc.INCREMENTAL_SUCCESS.sum / acc.INCREMENTAL_SUCCESS.count)
    : 0
  metrics.incrementalFailureAvg = acc.INCREMENTAL_FAILED.count
    ? Math.round(acc.INCREMENTAL_FAILED.sum / acc.INCREMENTAL_FAILED.count)
    : 0
}

function formatMsToMinSec(ms: number): string {
  if (!Number.isFinite(ms) || ms <= 0) return '0分0秒'
  const totalSec = Math.round(ms / 1000)
  const minutes = Math.floor(totalSec / 60)
  const seconds = totalSec % 60
  return `${minutes}分${seconds}秒`
}
</script>

<style scope lang="scss">
.build-analytics {
  .ba-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: 600;
  }
  .ba-search {
    margin-bottom: 12px;
  }
  .ba-form {
    display: flex;
    flex-wrap: wrap;
    gap: 8px 16px;
    align-items: center;
  }
  .ba-user-input {
    width: 220px;
  }
  .ba-metrics {
    .metric-card {
      .metric-title {
        color: #909399;
        font-size: 12px;
        margin-bottom: 6px;
      }
      .metric-value {
        font-size: 18px;
        font-weight: 600;
      }
    }
  }
}
</style>


